﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Goodway.Dao.Utility;

namespace ExcelImportComponent.Valider.Implement
{
    public class ValidFK:IVaild
    {
        #region IVaild 成员

        public List<ExcelImportValidMessage> DoValid(string validColumnName, List<Goodway.Dao.Utility.GoodwayEntity> entities, XElement validSetting, string schemaname)
        {
            if (validSetting.Attribute("TableName") == null) throw new Exception("主外键验证的TableName不能为空");
            if (validSetting.Attribute("PK") == null) throw new Exception("主外键验证的PK不能为空");
            if (validSetting.Attribute("DataSourceKey") == null) throw new Exception("主外键验证的DataSourceKey不能为空");
            if (validSetting.Attribute("TextColumn") == null) throw new Exception("主外键验证的TextColumn不能为空");
            if (validSetting.Attribute("Des") == null) throw new Exception("主外键验证的Des不能为空");
            string tableName = validSetting.Attribute("TableName").Value;
            string pk = validSetting.Attribute("PK").Value;
            string dataSourceKey = validSetting.Attribute("DataSourceKey").Value;
            string textColumn = validSetting.Attribute("TextColumn").Value;
            string des = validSetting.Attribute("Des").Value;
            IGoodwayEntityProvider provider = GoodwayEntityProviderFactory.GetEntityProvider();
            provider.ConStr = dataSourceKey;
            provider.TableName = tableName;
            List<GoodwayEntity> fkList = provider.GetAll();
            string message = string.Format("没有关联的{0}信息",des);
            List<ExcelImportValidMessage> returnValue = new List<ExcelImportValidMessage>();
            for (int i = 0; i < entities.Count; i++)
            {
                GoodwayEntity entity = entities[i];
                if (!string.IsNullOrEmpty(entity[validColumnName]))
                {
                    GoodwayEntity enumEntity = fkList.FirstOrDefault(p => p[textColumn] == entity[validColumnName]);
                    if (enumEntity == null)
                    {
                        ExcelImportValidMessage objMessage = new ExcelImportValidMessage(i.ToString(), validColumnName);
                        objMessage.Value = entity[validColumnName];
                        objMessage.ErrorMessage.Add(message);
                        returnValue.Add(objMessage);
                    }
                }
            }
            return returnValue;
            
        }
        #endregion
    }
}
